package controllers

import (
	"app/app/services"
	"app/dao"
	"app/models"

	"github.com/kataras/iris/v12"
)

type UserController struct {
	Ctx iris.Context
}

func (c *UserController) Post() *models.JsonResult {
	userModel := &models.UserModel{}
	if err := c.Ctx.ReadJSON(userModel); err != nil {
		return models.JsonErrorCode(501, err.Error())
	}
	isExist := services.UserService.FindByAccount(userModel.Account)
	if isExist.Id > 0 {
		return models.JsonErrorCode(501, "账号已存在")
	}
	userinfo := &dao.User{Name: userModel.Name, Account: userModel.Account, Password: userModel.Password, Roleid: userModel.Roleid}
	err := services.UserService.Save(userinfo, userModel.Members)
	if err != nil {
		return models.JsonErrorCode(501, err.Error())
	}
	return models.JsonSuccess()
}
func (c *UserController) Put() *models.JsonResult {
	userModel := &models.UserModel{}
	if err := c.Ctx.ReadJSON(userModel); err != nil {
		return models.JsonErrorCode(501, err.Error())
	}
	userinfo := &dao.User{Name: userModel.Name, Account: userModel.Account, Password: userModel.Password, Roleid: userModel.Roleid}
	err := services.UserService.Save(userinfo, userModel.Members)
	if err != nil {
		return models.JsonErrorCode(501, err.Error())
	}
	return models.JsonSuccess()
}
func (c *UserController) Get() *models.JsonResult {
	data := services.UserService.Fetch()
	return models.JsonData(data)
}

func (c *UserController) DeleteBy(id int) *models.JsonResult {
	services.UserService.Delete(id)
	return models.JsonSuccess()
}

func (c *UserController) GetBy(id int) *models.JsonResult {
	user := services.UserService.FindById(id)
	members := services.UserService.FetchMembers(id)
	userModel := &models.UserModel{
		Id:      user.Id,
		Name:    user.Name,
		Account: user.Account,
		Roleid:  user.Roleid,
		Members: members,
	}
	return models.JsonData(userModel)
}
